# coding=utf-8
import json
from abc import ABCMeta

import tornado.web

import WrapCursor
from CommonLib import CheckJsonKeys, CheckAuth
from database.models.DatabaseCommon import *
from database.models.MasterInfo import MasterInfo


class SetMasterInfoHandler(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        r = WrapCursor.WrapCursor()
        try:
            j = json.loads(self.request.body)
            longitude = j['longitude']
            latitude = j['latitude']
            ojson = j
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except Exception as e:
            self.write(r.Error(u'错误:' + str(u'请求数据错误')))

        s = Session()
        infos = s.query(MasterInfo).all()
        for i in infos:
            if i.name == u'longitude':
                i.value = longitude
            if i.name == u'latitude':
                i.value = latitude
        try:
            s.commit()
        except:
            self.write(r.Error(u'失败:写入数据库错误'))
            return
        self.write(r.Ok(u'成功'))
